package com.moyun.controller.org;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moyun.common.annotation.OperLog;
import com.moyun.common.aspect.BusinessType;
import com.moyun.model.common.R;
import com.moyun.model.po.org.SysOrgUserRoleEntity;
import com.moyun.model.vo.system.SysUserRoleVo;
import com.moyun.service.org.SysOrgUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 用户角色关联表 前端控制器
 * </p>
 *
 * @author yangboxuan
 * @since 2021-07-07
 */
@Api(tags = "系统用户角色")
@RestController
@RequestMapping("/org/sys-org-user-role")
public class SysOrgUserRoleController {
    @Autowired
    private SysOrgUserRoleService sysOrgUserRoleEntityService;

    /**
     * @return com.moyun.common.web.JsonResult
     * @Author yangboxuan
     * @Description 添加数据
     * @Date 2021-07-07
     * @Param [sysOrgUserRoleEntity]
     **/
    @ApiOperation("添加数据")
    @PostMapping(value = "/insert")
    @OperLog(operModul = "系统用户角色模块", operType = BusinessType.INSERT, operDesc = "添加数据")
    public R insert(@RequestBody SysUserRoleVo sysUserRoleVo) {
        // 先删除
        Integer userId = sysUserRoleVo.getUserId();
        QueryWrapper<SysOrgUserRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", sysUserRoleVo.getUserId());
        this.sysOrgUserRoleEntityService.remove(wrapper);
        // 再更新
        ArrayList<SysOrgUserRoleEntity> sysOrgUserRoleEntities = new ArrayList<>();
        List<Integer> roleIds = sysUserRoleVo.getRoleIds();
        for (Integer roleId : roleIds) {
            SysOrgUserRoleEntity sysOrgUserRoleEntity = new SysOrgUserRoleEntity();
            sysOrgUserRoleEntity.setUserId(userId);
            sysOrgUserRoleEntity.setOrgRoleId(roleId);
            sysOrgUserRoleEntities.add(sysOrgUserRoleEntity);
        }
        boolean flag = this.sysOrgUserRoleEntityService.saveBatch(sysOrgUserRoleEntities);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }
}

